<template>
  <div class="system-function">
    <div class="ppttit_sty">{{ $t('systemFunction') }}</div>
    <div class="search_box">
      <div class="label_sty">{{ $t('systemSelection') }}</div>
      <el-cascader
        ref="myCascader"
        :options="reactiveData.subsystemCategory"
        filterable
        clearable
        :placeholder="$t('selectCategory')"
        :show-all-levels="false"
        style="width: 100%"
        @change="handleCategoryChange"
      ></el-cascader>
    </div>
    <div class="infinite-list-wrapper">
      <ul class="list" :style="scrollHeight">
        <!-- reactiveData.loading -->
        <li
          v-for="item in reactiveData.subsystemList"
          :key="item.systemId"
          class="list-item"
          @click="showSystemFunctionDialog(item)"
        >
          <div class="img_sty">
            <img :src="item.systemMainImage" :alt="item.funcName" />
          </div>
          <div class="msg_sty">
            <div class="name ellipsis">{{ item.systemName }}</div>
            <div class="ellipsis">{{ item.systemDesc }}</div>
          </div>
        </li>
      </ul>
    </div>

    <Modal
      :visible="reactiveData.dialogForSystemFunction"
      :width="680"
      closeButton
      closeOnEsc
      @closed="closeSystemFunctionDialog"
    >
      <SystemFunctionDialog
        :data="reactiveData.selectedSubsystemFuncList"
        @confirm="handleConfirm"
        @cancel="closeSystemFunctionDialog"
      />
    </Modal>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, computed } from 'vue'
import fetch from '@/api/fetch'
import Modal from '@/components/Modal.vue'
import SystemFunctionDialog from './SystemFunctionDialog.vue'
import { ElCascader } from 'element-plus'
import { getDfsCustomObject } from '@/utils/process'
import useSystemFunction from '@/hooks/useSystemFunction'
import { getSystemFixedKey } from '@/mocks/customElement/system'
const reactiveData = reactive<any>({
  dialogForSystemFunction: false,
  subsystemList: [],
  subsystemCategory: [],
  selectedSubsystemFuncList: [],
  Category: '',
  pageNum: 1,
  total: 0,
})
const { createSystemFunctionSlide } = useSystemFunction()
const showSystemFunctionDialog = async (item: any) => {
  // 获取系统下的方法
  const { rows } = (await fetch.get(
    `/system/func/list?total=0&pageNum=1&pageSize=9999&systemId=${item.systemId}`
  )) as any

  // 查看详情，查列表没有返回field自定义数据
  const { data } = (await fetch.get(`/system/proposalSystem/${item.systemId}`)) as any

  reactiveData.selectedSubsystemFuncList = Object.assign({}, data, { funcList: rows })
  reactiveData.dialogForSystemFunction = true
}
const closeSystemFunctionDialog = () => {
  reactiveData.dialogForSystemFunction = false
}

// const handleNodeClick = async (item: any) => {
//   // 点击不是最下级就不触发
//   // if (item.children && item.children.length) return
//   activeItem.value = item.id
//   const res = getDfsCustomObject(reactiveData.subsystemCategory, item.id)
//   const queryString = new URLSearchParams(res).toString()
//   // 获取系统列表
//   const { rows } = (await fetch.get(
//     '/system/proposalSystem/list?total=0&pageNum=1&pageSize=99&' + queryString
//   )) as any
//   reactiveData.subsystemList = rows
// }

// 获取数据
const getData = async () => {
  reactiveData.loading = true
  try {
    const { rows, total } = (await fetch.get(
      `/system/proposalSystem/list?pageNum=${reactiveData.pageNum}&pageSize=999&${reactiveData.Category}0&orderByColumn=createTime&isAsc=desc`
    )) as any
    reactiveData.subsystemList = rows
    reactiveData.total = total
  }
  finally {
    reactiveData.loading = false
  }
}
const handleCategoryChange = (ids) => {
  if (!ids) {
    reactiveData.Category = ''
    reactiveData.pageNum = 1
    getData()
    return
  }
  const res = getDfsCustomObject(reactiveData.subsystemCategory, ids[ids.length - 1])
  const queryString = new URLSearchParams(res).toString()
  reactiveData.Category = queryString
  getData()
}
const scrollHeight = computed(() => {
  return 'height:' + ((window.innerHeight || document.documentElement.clientHeight) - 250) + 'px'
})

interface CheckField {
  label: string;
  key: string;
  value: string;
  check: boolean;
  aiValue: string;
}

interface SelectFunc {
  createBy: string;
  createTime: string;
  updateBy: string;
  updateTime: string;
  remark: string | null;
  funcId: number;
  systemId: number;
  funcName: string;
  funcDesc: string;
  funcMainImage: string;
  funcPrice: number;
  funcUnit: string;
  funcImages: string | null;
  isDelete: number;
  systemName: string;
  demandId: string | null;
  category1Name: string | null;
  projectId: string | null;
  notInFuncIds: string | null;
  systemIds: string | null;
  funcIds: string | null;
  aiFuncDesc: string | null;
}

interface ItemData {
  checkFields: CheckField[];
  selectFunc: SelectFunc[];
}

const handleConfirm = (item: ItemData) => {
  const { checkFields, selectFunc } = item
  const resultMap = new Map()

  // 确保如果未勾选默认数据，不显示
  resultMap.set(getSystemFixedKey('系统名称'), '')
  resultMap.set(getSystemFixedKey('系统功能介绍'), '')

  checkFields.forEach((item) => {
    resultMap.set(item.key, item.value || '')
    if (Object.hasOwn(item, 'aiValue')) {
      resultMap.set('aiValue', Reflect.get(item, 'aiValue'))
    }
  })

  selectFunc.forEach((item, index) => {
    resultMap.set(getSystemFixedKey('功能名称', index), item.funcName || '')
    resultMap.set(getSystemFixedKey('功能描述', index), item.funcDesc || '')
    resultMap.set(getSystemFixedKey('功能图片', index), item.funcMainImage || '')
    resultMap.set(getSystemFixedKey('功能智能描述', index), item.aiFuncDesc || '')
  })

  const fixedKeyArr = checkFields.map((item) => item.key.includes('field') && item.key).filter(Boolean)
  createSystemFunctionSlide(resultMap, fixedKeyArr, selectFunc.length)
  closeSystemFunctionDialog()
}

onMounted(async () => {
  // 获取系统分类
  const { rows } = (await fetch.get(
    '/system/category/list?pageNum=1&pageSize=9999&type=1&orderByColumn=createTime&isAsc=desc'
  )) as any
  const loopGetCategory = (data) => {
    return data.map((item) => {
      return {
        ...item,
        value: item.id,
        label: item.name,
        children: item.children?.length ? loopGetCategory(item.children) : null,
      }
    })
  }
  reactiveData.subsystemCategory = loopGetCategory(rows)
  getData()
})
</script>

<style lang="scss" scoped>
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.system-function {
  padding: 0 10px;
  .ppttit_sty {
    font-weight: bold;
    font-size: 14px;
    color: #333333;
    text-align: center;
    padding: 16px 0 12px;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 20px;
  }
  .search_box {
    margin-bottom: 20px;
    font-size: 14px;
    .label_sty {
      color: #999;
      margin-bottom: 18px;
    }
  }
  .infinite-list-wrapper {
    .list {
      overflow-y: scroll;
      .list-item {
        display: flex;
        margin-bottom: 10px;
        height: 80px;
        .img_sty {
          width: 96px;
          height: 80px;
          margin-right: 10px;
          border: 1px solid #eee;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            width: 96px;
            height: inherit;
            border-radius: 8px;
          }
        }
        .msg_sty {
          font-size: 12px;
          color: #999;
          padding: 2px 0;
          width: 120px;
          .name {
            font-size: 14px;
            font-weight: bold;
            color: #333;
            margin-bottom: 6px;
          }
        }
      }
    }
  }
  //   display: flex;
  //   .toolbar {
  //     max-width: 100px;
  //     flex: 1.4;
  //     .box {
  //       padding: 6px 0;
  //       p {
  //         border: 1px solid #000;
  //         padding: 6px;
  //         text-align: center;
  //       }
  //     }
  //   }
  //   .container {
  //     width: 0;
  //     flex: 3;
  //     padding: 12px;
  //     padding-right: 0;
  //     display: grid;
  //     grid-template-columns: 1fr 1fr;
  //     gap: 6px;
  //     figure {
  //       cursor: pointer;
  //       width: 100px;
  //     }
  //   }
}
.overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.active {
  background-color: #d8d8d8 !important;
  transition: background-color 0.3s;
}
::v-deep {
  .el-tree-node__content {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
  }
}
</style>
